'use strict';

const { Controller } = require('egg');

class UserController extends Controller {
  // 构造函数
  constructor(ctx) {
    super(ctx);
    this.userValidate = {
      username: {
        type: 'string',
        required: true,
        // u4e00-\u9fa5 是差不多20901个中文，基本涵盖了常用字
        format: /^[a-zA-Z0-9_\u4e00-\u9fa5]+[^_]{2,30}$/,
        message: '用户名的长度需要在3-30个字符之间',
      },
      password: {
        type: 'string',
        required: false,
        format: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_.]+)$)^[\w~!@#$%^&*()_.]{5,16}$/,
        message: '密码应为字母、数字、特殊符号(~!@#$%^&*()_.),两种及以上组合,5-16位字符串,如:123@b',
      },
      avatar: {
        type: 'string',
        required: false,
      },
    };
  }

  /**
   * 用户注册
   */
  async register() {
    const { ctx, service } = this;
    const { username, password, avatar } = ctx.request.body;
    ctx.validate(this.userValidate);
    if (!password) ctx.throw(401, '参数缺失')
    const userinfo = await service.user.register({ username, password, avatar });
    const { _id } = userinfo
    const token = service.token.get({ id: _id, username })
    ctx.body = { token, userinfo }
  }

  /**
   * 用户登录
   */
  async login() {
    const { ctx, service } = this;
    const { username, password } = ctx.request.body;
    ctx.validate(this.userValidate)
    if (!password) ctx.throw(401, '参数缺失')
    const userinfo = await service.user.login({ username, password })
    const { _id } = userinfo
    const token = service.token.get({ id: _id, username })
    ctx.body = { token, userinfo }
  }

  /**
   * 检测用户名是否存在
   */
  async checkUsername() {
    const { ctx, service } = this
    const { username } = ctx.query
    if (!username) ctx.throw(401, '参数缺失')
    const bool = await service.user.checkUsername(username)
    ctx.body = { bool }
  }

  /**
   * 更新用户信息
   */
  async update() {
    const { ctx, service } = this
    const { id } = ctx.params
    if (!id) ctx.throw(401, '参数缺失')
    ctx.validate(this.userValidate)
    const user = await service.user.update(id, ctx.request.body)
    ctx.body = user
  }

  /**
   * 获取用户列表
   */
  async list() {
    const { ctx, service } = this
    const { page = 1, pageSize = 20 } = ctx.query
    const { count, data } = await service.user.list(page * 1, pageSize * 1)
    ctx.body = {
      data,
      page,
      pageSize,
      totalPage: Math.ceil(count / pageSize),
      totalCount: count
    }
  }

  /**
   * 获取某个用户信息
   */
  async findById() {
    const { ctx, service } = this
    const { id } = ctx.params
    const user = await service.user.findById(id)
    ctx.body = user
  }
}

module.exports = UserController;
